package com.imooc.mall.service.impl;

import com.imooc.mall.common.ResultInfo;
import com.imooc.mall.common.ResultInfoUtil;
import com.imooc.mall.dao.UserMapper;
import com.imooc.mall.exception.MallException;
import com.imooc.mall.pojo.User;
import com.imooc.mall.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Optional;

@Service
@Slf4j
@SuppressWarnings("all")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;



    @Override
    public ResultInfo<User> register(User user) {

        //校验，username,email不能重复
        if (userMapper.countByUsername(user.getUsername())>0) {
            //throw new RuntimeException("该用户名已注册");
            //return ResultInfoUtil.error(0,"该用户名已注册");
            throw new MallException(0,"该用户名已注册");
        }
        if (userMapper.countByEmail(user.getEmail())>0) {
            //return ResultInfoUtil.error(0,"该邮箱已注册");
            throw new MallException(0,"该邮箱已注册");
        }
        //MD5摘要算法   spring自带
        String encodedPassword = DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8));
        user.setPassword(encodedPassword);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        //写入数据库
        int i = userMapper.insertSelective(user);
        if (i<1){
            throw new RuntimeException("注册失败");
        }
        return ResultInfoUtil.success();
    }

    @Override
    public ResultInfo<User> login(String username,String password) {
        //推荐用一个字段查，数据库username建立了唯一索引
        Optional<User> user = Optional.ofNullable(userMapper.findUserByUsername(username));
        if (user.isPresent()) {
            //比较密码
            if (DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)).
                    equalsIgnoreCase(user.get().getPassword())) {
                user.get().setPassword(null);
                return ResultInfoUtil.success(user.get());
            }
        }
        throw  new MallException(3,"用户名或密码错误");

    }
}
